package xyz.zq.cloud.admin.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.zq.cloud.admin.mapper.AccountMapper;
import xyz.zq.cloud.admin.service.AccountService;
import xyz.zq.cloud.admin.service.MenuService;
import xyz.zq.cloud.admin.service.RoleService;
import xyz.zq.cloud.bs.api.dto.AccountDTO;
import xyz.zq.cloud.bs.api.dto.UserInfo;
import xyz.zq.cloud.bs.api.entity.Account;
import xyz.zq.cloud.bs.api.entity.Role;
import xyz.zq.cloud.bs.api.vo.MenuVO;
import xyz.zq.cloud.common.security.util.SecurityUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 租户商户用户 服务实现类
 * </p>
 *
 * @author hzq
 * @since 2020-05-11
 */
@Slf4j
@Service
@AllArgsConstructor
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    private final RoleService roleService;
    private final MenuService menuService;

    @Override
    public UserInfo getUserInfo(Account account) {
        UserInfo userInfo = new UserInfo();
        userInfo.setAccount(account);

        //设置角色列表  （ID）
        List<Integer> roleIds = roleService
                .listRolesByUserId(account.getId())
                .stream().map(Role::getId)
                .collect(Collectors.toList());
        userInfo.setRoles(ArrayUtil.toArray(roleIds, Integer.class));

        //设置权限列表（menu.permission）
        Set<String> permissions = new HashSet<>();
        roleIds.forEach(roleId -> {
            List<String> permissionList = menuService.getMenuByRoleId(roleId)
                    .stream()
                    .filter(menu -> StrUtil.isNotEmpty(menu.getPermission()))
                    .map(MenuVO::getPermission)
                    .collect(Collectors.toList());
            permissions.addAll(permissionList);
        });
        userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
        return userInfo;
    }


    @Override
    public IPage getUserWithRolePage(Page page, AccountDTO accountDTO) {
        accountDTO.setCompanyId(SecurityUtils.getCompanyId());
        return baseMapper.getUserVosPage(page, accountDTO);
    }
}
